package netbayServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.String.StringUtil;
import util.jQgrid.JQGridContainer;
import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;
import util.jQgrid.JSONUtil;

import netbay.NetbayUtility;
import netbay.TransactionManager;

/**
 * Servlet implementation class ViewServlet
 */
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static String recvTcdStatus = "";
	public static String recvRdStatus = "";
	public static String beginSendJpmcStatus = "";
	public static String finSendJpmcStatus = "";
	public static String recvJpmcStatus = "";
	public static String sendTcdStatus = "";
	public static String sendRdStatus = "";
	public static String finSendTcdStatus = "";
	public static String finSendRdStatus = "";
	public static String resendSFTPStatus = "";
	public static String redownloadSFTPStatus = "";
	public static String redownloadSFTPRDStatus = "";
	

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewServlet() {
		super();
	}

	public void init() {
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		NetbayUtility.init(configPath);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
        response.setContentType("text/json;charset=utf-8");
        HttpSession session = request.getSession();
        String url = "";
        String userId = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("userId")))) ? (String)session.getAttribute("userId"): "null");
        if(!(userId.equals("null"))){
        	System.out.println("in do get view servlet");
        	url = "/TrackViewer.jsp";
        	request.setAttribute("fromTime",curTime("today"));
        	request.setAttribute("toTime",curTime("today"));
        	request.setAttribute("recvTcdStatus", recvTcdStatus);
        	request.setAttribute("beginSendJpmcStatus", beginSendJpmcStatus);
        	request.setAttribute("finSendJpmcStatus", finSendJpmcStatus);
        	request.setAttribute("recvJpmcStatus", recvJpmcStatus);
        	request.setAttribute("sendTcdStatus", sendTcdStatus);
        	request.setAttribute("finSendTcdStatus",finSendTcdStatus);
        	request.setAttribute("resendSFTPStatus", resendSFTPStatus);
        	request.setAttribute("redownloadSFTPStatus", redownloadSFTPStatus);
        }
        else{
        	url = "/Login.jsp";
        }
        try{
        	request.getRequestDispatcher(url).forward(request, response);
		} catch (Exception ex) {
	        ex.printStackTrace();
	    }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String strJson = "{}";
		String userPath = request.getServletPath();
		TransactionManager tm = new TransactionManager();

	     if (userPath.equals("/ViewServlet/BindGrdTransaction")) {
			 String page = request.getParameter("page"); // get the requested page
	         String limit = request.getParameter("rows"); // get how many rows we want to have into the grid
	         String sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
	         String sord = request.getParameter("sord"); // get the direction
	         
	         
	         String fromTime = (!StringUtil.isNullOrEmpty(request.getParameter("fromTime"))) ? request.getParameter("fromTime").trim() : "";
	         String toTime = (!StringUtil.isNullOrEmpty(request.getParameter("toTime"))) ? request.getParameter("toTime").trim() : "";
	         String type = (!StringUtil.isNullOrEmpty(request.getParameter("ddlCustomType"))) ? request.getParameter("ddlCustomType").trim() : "";
	         String status= (!StringUtil.isNullOrEmpty(request.getParameter("ddlStatus"))) ? request.getParameter("ddlStatus").trim() : "";
	         String converID = (!StringUtil.isNullOrEmpty(request.getParameter("conversationId"))) ? request.getParameter("conversationId").trim() : "";
			 
	         String reJPMCTCD = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("reJPMCTCD")))) ? (String)session.getAttribute("reJPMCTCD"): "null");
	         String reTCDTCD = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("reTCDTCD")))) ? (String)session.getAttribute("reTCDTCD"): "null");
	         try{
		         fromTime = dateToDecimal(fromTime,"from");
				 toTime = dateToDecimal(toTime,"to");
	         
				 List result = null;
				 Integer all = 0;
		
				 all = tm.getDisplayTransaction(fromTime,toTime,type,status,converID,"TCD");
				 result = tm.getDisplayTransaction(fromTime,toTime,type,status,converID,reJPMCTCD,reTCDTCD,"TCD",page,limit,sidx,sord);
			
				 strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), all, result);
				 //out.println(strJson);
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
	         }
	         out.println(strJson);
	     }
	}
	
	
	public String curTime(String type){
		String curTime = "";
		Date now = new Date();
		String date;
		String year = Integer.toString(now.getYear()+1900);
		String month = Integer.toString(now.getMonth()+1);
		if(type.equals("today")){
			date = Integer.toString(now.getDate());
		}else{
			date = Integer.toString(now.getDate()-1);
		}
//		String hour = Integer.toString(now.getHours());
//		String minute = Integer.toString(now.getMinutes());
//		String second = Integer.toString(now.getSeconds());
//		
//		 if(hour.length()==1)hour = "0"+hour;
//		 if(minute.length()==1)minute = "0"+minute;
//		 if(second.length()==1)second = "0"+second;
		 if(date.length()==1)date = "0"+date;
		 if(month.length()==1)month = "0"+month;
		
		curTime +="'";
		curTime +=year;
		curTime +="-";
		curTime +=month;
		curTime +="-";
		curTime +=date;
		curTime +=" ";
//		curTime +=hour;
//		curTime +=":";
//		curTime +=minute;
//		curTime +=":";
//		curTime +=second;
		curTime +="'";
		
		return curTime;
	}
	
	public String dateToDecimal (String date,String type) throws Exception{
		 String[] splitDate = date.split("[-]");
		 String dateToDecimal = "";
		 for(int i =0;i<splitDate.length;i++){
			 dateToDecimal = dateToDecimal+splitDate[i];
		 }
		 
		 if(type.equals("from"))dateToDecimal = dateToDecimal+"000000.000";
		 if(type.equals("to"))dateToDecimal = dateToDecimal+"999999.999";
		 return dateToDecimal;
	}
	
}
